Encode and decode strings

Time: O(N); Space: O(1); medium

Design an algorithm to encode a list of strings to a string.

The encoded string is then sent over the network and is decoded back to the original list of strings.

Please implement encode and decode

Example 1:

Input: strs = [“lint”,“code”,“love”,“you”]

Output: [“lint”,“code”,“love”,“you”]

Explanation:

  • One possible encode method is: “lint:;code:;love:;you”

Example 2:

Input: strs = [“we”, “say”, “:”, “yes”]

Output: [“we”, “say”, “:”, “yes”]

Explanation:

  • One possible encode method is: “we:;say:;:::;yes”

[1]:
class Codec(object):

    def encode(self, strs):
        """Encodes a list of strings to a single string.
        :type strs: List[str]
        :rtype: str
        """
        encoded_str = ""
        for s in strs:
            encoded_str += "%0*x" % (8, len(s)) + s
        return encoded_str

    def decode(self, s):
        """Decodes a single string to a list of strings.
        :type s: str
        :rtype: List[str]
        """
        i = 0
        strs = []
        while i < len(s):
            l = int(s[i : i+8], 16)
            strs.append(s[i+8 : i+8+l])
            i += 8 + l
        return strs
[10]:
c = Codec()

strs = ["lint","code","love","you"]
enc_strs = c.encode(strs)
# print(enc_strs)      # 00000004lint00000004code00000004love00000003you
assert c.decode(enc_strs) == ["lint","code","love","you"]

strs = ["we", "say", ":", "yes"]
enc_strs = c.encode(strs)
# print(enc_strs)    # 00000002we00000003say00000001:00000003yes
assert c.decode(enc_strs) == ["we", "say", ":", "yes"]